package com.cupdata.zicon.jdk7concurrent.chapter4;

import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * You use the cancel() method of the Future interface when you want to cancel a
 * task that you have sent to an executor. Depending on the parameter of the
 * cancel() method and the status of the task, the behavior of this method is
 * different:
 * 
 * If the task has finished or has been canceled earlier or it can't be canceled
 * for other reasons, the method will return the false value and the task won't
 * be canceled.
 * 
 * If the task is waiting in the executor to get a Thread object that will
 * execute it, the task is canceled and never begins its execution. If the task
 * is already running, it depends on the parameter of the method. The cancel()
 * method receives a Boolean value as a parameter. If the value of that
 * parameter is true and the task is running, it will be canceled. If the value
 * of the parameter is false and the task is running, it won't be canceled.
 * 
 * @author SunYabing
 *
 */
public class CancelingTask {

	public CancelingTask() {

	}

	public static void main(String[] args) {
		ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors
				.newCachedThreadPool();

		Task34 task = new Task34();
		System.out.printf("Main: Executing the Task\n");
		Future<String> result = executor.submit(task);

		try {
			TimeUnit.SECONDS.sleep(2);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		System.out.printf("Main: Canceling the Task\n");
		result.cancel(true);

		System.out.printf("Main: Canceled: %s\n", result.isCancelled());
		System.out.printf("Main: Done: %s\n", result.isDone());

		executor.shutdown();
		System.out.printf("Main: The executor has finished\n");

	}

}

class Task34 implements Callable<String> {
	@Override
	public String call() throws Exception {
		while (true) {
			System.out.printf("Task: Test\n");
			Thread.sleep(100);
		}
	}
}
